using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using mesoBoard.Data.Repositories;
using mesoBoard.Data;
using mesoBoard.Web;
using mesoBoard.Web.Core;
using mesoBoard.Services;

namespace mesoBoard.Web.Controllers
{
    [Authorize]
    public partial class MessagesController : mesoBoardController
    {
        public MessagesController()
        {
            SetCrumbs("User CP", "User CP");
        }

        [HttpGet]
        public ActionResult SendMessage(string ToUsername)
        {
            ViewData["BreadCrumb"] = "Send Message";
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SendMessage(Message TheMessage, string ToUsername)
        {
            ViewData["BreadCrumb"] = "Send Message";

            if (!Repositories.Users.UserExists(ToUsername))
                ModelState.AddModelError("ToUsername", "No such user");

            if (ToUsername.ToLower() == CurrentUser.UsernameLower)
                ModelState.AddModelError("ToUsername", "You can't send a message to yourself!");

            if (string.IsNullOrEmpty(TheMessage.Text))
                ModelState.AddModelError("Text", "Enter a message");

            if (ModelState.IsValid)
            {
                User ToUser = Repositories.Users.GetUser(ToUsername);
                TheMessage.ToUserID = ToUser.UserID;
                TheMessage.DateSent = DateTime.UtcNow;
                TheMessage.FromUserID = CurrentUser.UserID;
                TheMessage.Text = TheMessage.Text;
                TheMessage.Subject = TheMessage.Subject ?? "<No Subject>";
                Repositories.Messages.SendMessage(TheMessage);
                SetSuccess("Message sent to <b>" + ToUsername + "</b>");
                string messageURL = Url.Action("ViewMessage", "Messages", new { MessageID = TheMessage.MessageID });
                Emailing.NewMessage(TheMessage, ToUser, messageURL);
                return RedirectToAction("Inbox", new { Box = "All" });
            }
            else
            {
                SetError("Invalid information provided, please correct");
                return View();
            }
        }

        [HttpGet]
        public ActionResult ViewMessage(int MessageID)
        {
            ViewData["BreadCrumb"] = "View Message";
            Message TheMessage = Repositories.Messages.GetMessage(MessageID);
            if (TheMessage != null && (TheMessage.FromUserID == CurrentUser.UserID || TheMessage.ToUserID == CurrentUser.UserID))
            {
                ViewData["UserIs"] = (TheMessage.ToUserID == CurrentUser.UserID) ? "To" : "From";
                if (TheMessage.ToUserID == CurrentUser.UserID)
                {
                    Repositories.Messages.SetIsRead(TheMessage);
                }
                return View(TheMessage);
            }
            else
            {
                SetError("Error retrieving the message, no message found");
                return View();
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ViewMessage(string ReplyMessage, int MessageID, int MessageToUserID, string Subject)
        {
            ViewData["BreadCrumb"] = "View Message";
            Message TheMessage = Repositories.Messages.GetMessage(MessageID);

            if (string.IsNullOrWhiteSpace(ReplyMessage))
                ModelState.AddModelError("ReplyMessage", "Please enter a reply");

            if (ModelState.IsValid)
            {
                Message NewMessage = new Message();
                NewMessage.Subject = Subject;
                NewMessage.FromUserID = CurrentUser.UserID;
                NewMessage.ToUserID = MessageToUserID;
                NewMessage.Text = ReplyMessage;
                NewMessage.DateSent = DateTime.UtcNow;
                Repositories.Messages.SendMessage(NewMessage);

                User ToUser = mbServices.Users.GetUser(MessageToUserID);
                string messageURL = Url.Action("ViewMessage", "Messages", new { MessageID = TheMessage.MessageID });
                Emailing.NewMessage(NewMessage, ToUser, messageURL);
                SetSuccess("Reply sent to <b>" + NewMessage.UserTo.Username + "</b>");
                return RedirectToAction("Inbox");
            }
            else
            {
                SetError("Please enter a reply message");
                return View(TheMessage);
            }
        }

        [HttpGet]
        public ActionResult Inbox(string Box)
        {
            ViewData["BreadCrumb"] = "Inbox";

            IEnumerable<Message> AllMessages = Repositories.Messages.GetAllMessagesByUser(CurrentUser);
            IEnumerable<Message> ToMessages = AllMessages.Where(x => x.ToUserID == CurrentUser.UserID && x.ToDelete == false);
            IEnumerable<Message> FromMessages = AllMessages.Where(x => x.FromUserID == CurrentUser.UserID && x.FromDelete == false);

            IEnumerable<Message> NewMessages = ToMessages.Where(x => x.IsRead == false);
            IEnumerable<Message> ReadMessages = ToMessages.Where(x => x.IsRead == true);
            IEnumerable<Message> SentMessages = FromMessages;


            ViewData["New"] = NewMessages;
            ViewData["Sent"] = FromMessages;

            ViewData["NewMessages"] = NewMessages.Count() > 0 ? NewMessages : null;
            ViewData["ReadMessages"] = ReadMessages.Count() > 0 ? ReadMessages : null;
            ViewData["SentMessages"] = SentMessages.Count() > 0 ? SentMessages : null;

            if (Box == "Sent")
            {
                ViewData["BreadCrumb"] = "Sent";
                return View("Sent", FromMessages.OrderByDescending(x => x.DateSent));
            }
            else
            {
                return View("Inbox", ToMessages.OrderByDescending(x => x.DateSent));
            }
        }

        [HttpPost]
        public ActionResult Inbox(int[] msgID, string Box, string DoAction)
        {
            ViewData["BreadCrumb"] = "Inbox";

            if (msgID == null)
            {
                SetNotice("You must select a message(s) to " + DoAction);
                return RedirectToAction("Inbox", new { Box = Box });

            }
            else if (DoAction != "Delete" && DoAction != "Mark As Read")
            {
                SetNotice("You must specify an action to take");
                return RedirectToAction("Inbox", new { Box = Box });
            }

            if (DoAction == "Delete")
            {
                foreach (int mid in msgID)
                {
                    Repositories.Messages.DeleteMessage(mid);
                }

                SetSuccess("Message(s) deleted");
            }
            else if (DoAction == "Mark As Read")
            {
                foreach (int mid in msgID)
                {
                    Message TheMessage = Repositories.Messages.GetMessage(mid);
                    Repositories.Messages.SetIsRead(TheMessage);
                }

                SetSuccess("Message(s) marked as read");
            }

            return RedirectToAction("Inbox", new { Box = Box });
        }
    }
}
